<?php

namespace wether;

//天气接口
class wether
{
	public $wetherCode;

	public function __construct()
	{
        // 从城市天气对应关系文件里提取数据
		$txtCode = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'wetherCode.txt');
		$this->wetherCode = json_decode($txtCode, true);
	}

	// 根据城市名称代码查询天气
	public function wetherByCity($city)
	{
		$code = $this->wetherCode[$city]['wetherCode'];
		return $this->getWether($code);
	}
	// 根据城市代码查询天气
	public function wetherByCode($cityCode)
	{
		$code = "";
		foreach($this->wetherCode as $wether){
			if($wether['cityCode'] == $cityCode){
				$code = $wether['wetherCode'];
			}
		}
		if($code){
			return $this->getWether($code);
		}
	}

	// 查询天气信息
	public function getWether($code)
	{
        // GET请求天气网查询当前天气
		$url = "https://weather.cma.cn/api/weather/view?stationid=" . $code;
		return json_decode(file_get_contents($url), true)['data'];
	}
}